package com.itheima.httpClient;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.Arrays;

public class HttpClientPost {
    public static void main(String[] args) throws Exception{
        String urlIndex="http://www.itcast.cn";

        CloseableHttpClient client = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(urlIndex);

        httpPost.setHeader("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36");

        ArrayList<BasicNameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("username","zhangsan"));
        list.add(new BasicNameValuePair("password","123456"));
        list.add(new BasicNameValuePair("age","20"));


        HttpEntity httpEntity=new UrlEncodedFormEntity(list);

        httpPost.setEntity(httpEntity);

        //发送请求
        CloseableHttpResponse resp = client.execute(httpPost);

        int stat = resp.getStatusLine().getStatusCode();
        if(stat==200){


            HttpEntity entity = resp.getEntity();
            String s = EntityUtils.toString(entity,"UTF-8");
            System.out.println(s);
        }

        resp.close();
        client.close();
    }
}
